<template>
	<el-drawer direction="rtl" v-model="dialogVisible" :title="dialogTitle" size="90%">
		<ContentWrap>
			<!-- 搜索工作栏 -->
			<el-form :v-model="form" label-width="120px">
				<el-row>
					<el-col :span="12">
						<el-form-item label="水表名称"> {{ form.waterName }}（电池状态：<dict-tag :type="DICT_TYPE.VOLTAGE_STATUS" :value="form.voltageStatus" />） </el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="水表编码"> {{ form.waterNo }}（IMEI：{{ form.waterImei }}） </el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="水表厂家">
							<dict-tag :type="DICT_TYPE.WATER_FACTORY" :value="form.factoryCode" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="使用模式">
							<dict-tag :type="DICT_TYPE.WATER_MODE_FLAG" :value="form.modeFlag" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="安装位置">
							<el-tag type="info" effect="plain">{{ form.bindAddresses }}</el-tag>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="闸控">
							<dict-tag :type="DICT_TYPE.VALVE_STATUS" :value="form.valveStatus" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="设备时钟">{{ form.waterClock }}</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="抄收时间">
							<el-tag type="danger" effect="plain">{{ formatDate(form.lastReadTime, 'YYYY-MM-DD HH:mm:ss') }}</el-tag>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="累计流量"> {{ formatToFraction(form.totalUseData || 0) }}m³ </el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="结算日流量"> {{ formatToFraction(form.settleDayData || 0) }}m³ </el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="瞬时流量"> {{ formatToFraction(form.currentData || 0) }}m³ </el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="上月流量"> {{ formatToFraction(form.lastData || 0) }}m³ </el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="信号强度">{{ form.waterRssi }}</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="电池电压">{{ form.waterVoltage }}</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="账户余额">
							<el-tag type="danger" effect="plain">{{ form.balance }}{{ form.factoryCode == 1 ? '吨' : '元' }}</el-tag>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="管理人员">
							<el-tag v-for="item in form.authManagerRespVOS" :key="item.authUserId" type="success" effect="plain">{{ item.authUserName }}</el-tag>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="银联账户">
							<el-tag type="danger" effect="plain" v-if="form.ownMeterConfigRespVO != null">{{ form.ownMeterConfigRespVO.memberUserName }}（{{ form.ownMeterConfigRespVO.matCode }}）</el-tag>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="账户有效期">
							<el-tag type="danger" effect="plain" v-if="form.ownMeterConfigRespVO != null">{{ formatDate(form.ownMeterConfigRespVO.matExpiresTime, 'YYYY-MM-DD') }}</el-tag>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<el-form label-width="10px" :inline="false" v-if="form.externalLinkId != null && form.externalLinkId != undefined">
				<el-form-item>
					<span style="margin-left: 5px; color: green">与水表系统同步后返回的ID值为： {{ form.externalLinkId }}</span>
					<span style="margin-left: 5px; color: red">以下功能均调用水表系统（用于数据查询）</span>
				</el-form-item>
				<el-form-item>
					<el-button type="success" @click="oper('cb')">抄表</el-button>
					<span style="margin-left: 5px; color: gray">从水表系统中同步表数据</span>
				</el-form-item>
				<el-row>
					<el-col :span="12">
						<el-form-item>
							<el-button type="success" @click="oper('kz')">执行开阀</el-button>
							<span style="margin-left: 5px; color: gray">开阀后将通水</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item>
							<el-button type="danger" @click="oper('gz')">执行关阀</el-button>
							<span style="margin-left: 5px; color: gray">关阀后将停水</span>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item v-if="isOpenFromRoom == false">
							<el-button type="danger" @click="oper('sfcz')">水费充值（手动）</el-button>
							<span style="margin-left: 5px; color: gray">进行水费充值（不通过支付）</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item>
							<el-button type="danger" @click="oper('yeql')">余额清零</el-button>
							<span style="margin-left: 5px; color: gray">该操作会根据水表余额——未出账单天数扣减具体费用后进行清零</span>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item>
							<el-button type="primary" @click="oper('czcx2')">充值查询-中微</el-button>
							<span style="margin-left: 5px; color: gray">查询（水表系统）最近N笔充值数据</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item>
							<el-button type="primary" @click="oper('yscx')">用水查询-外系统</el-button>
							<span style="margin-left: 5px; color: gray">查询（水表系统）最近N笔用水数据</span>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</ContentWrap>
	</el-drawer>
	<WaterPayOrderQuery ref="payOrderQueryRef" />
	<WaterUserQuery ref="useQueryRef" />
</template>
<script lang="ts" setup>
	import { DICT_TYPE } from '@/utils/dict'
	import { formatDate } from '@/utils/formatTime'
	import { WaterApi } from '@/api/zwsj/water'
	import { ElNotification } from 'element-plus'
	import WaterPayOrderQuery from '@/views/zwsj/water/WaterPayOrderQuery.vue'
	import WaterUserQuery from '@/views/zwsj/water/WaterUserQuery.vue'

	defineOptions({ name: 'WaterView' })

	const message = useMessage()

	const dialogVisible = ref(false) // 弹窗的是否展示
	const dialogTitle = ref('水表详情') // 弹窗的标题
	const waterIdRef = ref<number>(0)
	const isOpenFromRoom = ref<boolean>(true)

	const form = ref({
		id: undefined,
		commId: undefined,
		factoryCode: undefined,
		modeFlag: undefined,
		waterName: undefined,
		waterNo: undefined,
		waterImei: undefined,
		waterClock: undefined,
		lastReadTime: undefined,
		waterRssi: undefined,
		waterVoltage: undefined,
		balance: undefined,
		totalUseData: undefined,
		settleDayData: undefined,
		currentData: undefined,
		lastData: undefined,
		settleDay: undefined,
		valveStatus: undefined,
		voltageStatus: undefined,
		feeStatus: undefined,
		matCodeId: undefined,
		externalLinkId: undefined,
		sort: undefined,
		useStatus: undefined,
		ownMeterConfigRespVO: {
			memberUserName: undefined,
			matCode: undefined,
			matExpiresTime: undefined,
		},
		authManagerRespVOS: [],
	})

	/** 打开弹窗 */
	const open = async (meterIdT: number) => {
		dialogVisible.value = true
		waterIdRef.value = meterIdT

		isOpenFromRoom.value = false
		getWater(meterIdT)
	}

	const openByRoomId = async (roomId: number) => {
		dialogVisible.value = true
		dialogTitle.value = '房间水表详情'
		getWaterByRoomId(roomId)
	}
	defineExpose({ open, openByRoomId })

	const getWaterByRoomId = async (roomId: number) => {
		form.value = await WaterApi.getRoomRelaWater(roomId)
		waterIdRef.value = form.value.id
	}

	const getWater = async (waterId: number) => {
		form.value = await WaterApi.getWater(waterId)
	}

	/**
	 * 将一个整数转换为分数保留三位小数
	 * @param num
	 */
	const formatToFraction = (num: number | string | undefined): string => {
		if (typeof num === 'undefined') return '0.000'
		const parsedNumber = typeof num === 'string' ? parseFloat(num) : num
		return (parsedNumber / 1000.0).toFixed(3)
	}

	const payOrderQueryRef = ref()
	const useQueryRef = ref()
	// console.log('payOrderQueryRef', payOrderQueryRef)
	// console.log('useQueryRef', useQueryRef)
	const oper = async (flag: string) => {
		const waterId: number = waterIdRef.value
		//cb bd qxbd lz hz dqdj xgdj xgtzje ydcx
		switch (flag) {
			case 'cb': {
				//抄表
				message
					.confirm('此操作将从水表平台获取最新数据, 是否继续?', '抄表')
					.then(() => {
						WaterApi.updateWaterParamByCallReadOut(waterId).then(data => {
							if (data) {
								message.notifySuccess('抄表成功')
								getWater(waterId)
							}
						})
					})
					.catch(e => {})
				break
			}
			case 'gz': {
				//关阀
				message
					.confirm('此操作将会关阀（将不能用水）, 是否继续?', '关阀')
					.then(() => {
						WaterApi.closeValve(waterId).then(data => {
							if (data) {
								message.notifySuccess('关阀成功')
								getWater(waterId)
							}
						})
					})
					.catch(e => {})
				break
			}
			case 'kz': {
				//开阀
				message
					.confirm('此操作将会开阀（将能用水）, 是否继续?', '开阀')
					.then(() => {
						WaterApi.openValve(waterId).then(data => {
							if (data) {
								message.notifySuccess('开阀成功')
								getWater(waterId)
							}
						})
					})
					.catch(e => {
						ElNotification({ type: 'info', message: e })
					})
				break
			}
			case 'sfcz': {
				// const data = await ConfigApi.getConfigKey('handle_water_recharge')
				// if('1' !== data){
				//   message.notifyError('暂不支持')
				//   return false;
				// }
				//水表进行充值
				message.confirm('此操作将会对水表进行充值, 是否继续?', '水费充值').then(() => {
					ElMessageBox.prompt('该水表余额：(' + form.value.balance + '元)，请输入本次要充值的金额', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						inputPattern: /^[1-9]\d*\.\d+$|^0\.\d+$|^[1-9]\d*$|^0$/,
						inputErrorMessage: '金额不正确',
					}).then(({ value }) => {
						WaterApi.recharge(waterId, '' + parseFloat(value) * 100).then(data => {
							if (data) {
								message.notifySuccess('充值水费成功')
								getWater(waterId)
							}
						})
					})
				})
				break
			}
			case 'yeql': {
				//余额清零
				message.confirm('此操作会将水表余额清零, 是否继续?', '余额清零').then(() => {
					WaterApi.clearWaterBalance(waterId).then(data => {
						if (data) {
							message.notifySuccess('清零成功')
							getWater(waterId)
						}
					})
				})
				break
			}
			case 'czcx2': {
				//充值查询
				payOrderQueryRef.value.open(waterId)
				break
			}
			case 'yscx': {
				//充值查询
				useQueryRef.value.open(waterId)
				break
			}
		}
	}
</script>
